
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using Db4objects;
using System.Collections.Generic;
namespace NCS_CS
{


    public partial class Mcsy : System.Windows.Forms.UserControl
    {
        [System.Runtime.InteropServices.ProgId("EVpowerEventArgs_NET.EVpowerEventArgs")]
        public sealed class EVpowerEventArgs : System.EventArgs
        {
            public double x;
            public double y;
            public EVpowerEventArgs(double x, double y)
                : base()
            {
                this.x = x;
                this.y = y;
            }
        }
        public event EVpowerEventHandler EVpower;
        public delegate void EVpowerEventHandler(System.Object Sender, EVpowerEventArgs e);
        [System.Runtime.InteropServices.ProgId("StatusJieQiEventArgs_NET.StatusJieQiEventArgs")]
        public sealed class StatusJieQiEventArgs : System.EventArgs
        {
            public bool b;
            public StatusJieQiEventArgs(bool b)
                : base()
            {
                this.b = b;
            }
        }

        //public enum kgindex
        //{
        //    开 = true,
        //    关 = false
        //}

        public class Cmd
        {
            public vlvindex vindex;
            public bool isopen;
            public Cmd(vlvindex vi, bool vo)
            {
                vindex = vi;
                isopen = vo;
            }
        }
        public sealed class startTaskEventArgs : System.EventArgs
        {
            public int id;
            public startTaskEventArgs(int id)
                : base()
            {
                this.id = id;
            }
        }
        public enum csyState
        {
            enmReady = 0,
            enmAddSample = 1,
            enmSync = 2,
            enmShoudong = 3,
            enmAuto = 4,
            enmYuchuli = 5,
            enmDebugSample=6
        }
        public enum vlvindex
        {
            enmKailu = 0,
            enmChongxi = 1,
            enmFengding = 2,
            enmJiayang = 3,
            enmTouyang = 4,
            enmJieqi = 5,
            enmBili = 6
        }
        public enum diIndex
        {
            enmZongyang = 0,
            enmDongli = 1,
            enmLushua = 3,
            enmLuhou = 2,
            enmShenglu = 4
        }
        public enum timerState
        {
            enmGpPower = 4,
            enmYali = 1,
            enmPaikong = 2,
            enmvlv7 = 3
        }
        public enum myerrNum
        {
            enmNeedreset = -1,
            //需要复位frmMain start stop 状态
            enmNoErr = 0,
            //
            enmErryali = 1,
            //1, "氧气压力未达到")
            enmErrCaoshi = 2,
            //2,通讯超时
            enmErrCom = 3,
            //通讯错误
            enmErrState = 4
            //通讯错误
        }
        [System.Runtime.InteropServices.ProgId("sigFinishEventArgs_NET.sigFinishEventArgs")]
        public sealed class sigFinishEventArgs : System.EventArgs
        {
            public Sig s;
            public sigFinishEventArgs(Sig v)
                : base()
            {
                this.s = v;
            }
        }
        [System.Runtime.InteropServices.ProgId("StatusStrEventArgs_NET.StatusStrEventArgs")]
        public sealed class StatusStrEventArgs : System.EventArgs
        {
            public string s;
            public StatusStrEventArgs(string s)
                : base()
            {
                this.s = s;
            }
        }
        public event StatusStrEventHandler StatusStr;
        public delegate void StatusStrEventHandler(System.Object Sender, StatusStrEventArgs e);
        //
        public sealed class endTaskEventArgs : System.EventArgs
        {
            public endTaskEventArgs()
                : base()
            {
            }
        }
        public event endTaskEventHandler endTask;
        public delegate void endTaskEventHandler(System.Object Sender, endTaskEventArgs e);
        //
        public sealed class myStatusEventArgs : System.EventArgs
        {
            public double u, v, jh, zh, sw;
            public myStatusEventArgs(double u, double v, double jh, double zh, double sw)
                : base()
            {
                this.u = u;
                this.v = v;
                this.jh = jh;
                this.zh = zh;
                this.sw = sw;
            }
        }
        public event myStatusEventHandler myStatus;
        public delegate void myStatusEventHandler(System.Object Sender, myStatusEventArgs e);

        public event StatusJieQiEventHandler EVjieQi;
        public delegate void StatusJieQiEventHandler(System.Object Sender, StatusJieQiEventArgs e);

        public event startTaskEventHandler startTask;
        public delegate void startTaskEventHandler(System.Object Sender, startTaskEventArgs e);

        public event dataReceiveEventHandler dataReceive;
        public delegate void dataReceiveEventHandler(System.Object Sender, dataReceiveEventArgs e);
        public event dataReceiveMultiEventHandler dataReceiveMulti;
        public delegate void dataReceiveMultiEventHandler(System.Object Sender, dataReceiveMultiEventArgs e);
        public event dataEndEventHandler dataEnd;
        public delegate void dataEndEventHandler(System.Object Sender, dataEndEventArgs e);

        public event FinishSIGEventHandler FinishSIG;
        public delegate void FinishSIGEventHandler(System.Object Sender, sigFinishEventArgs e);

        public event myErrEventHandler myErr;
        public delegate void myErrEventHandler(System.Object Sender, myErrEventArgs e);

        public event evResetEventHandler evReset;
        public delegate void evResetEventHandler(System.Object Sender, System.EventArgs e);
        private TimerExt3 tx_gl;
        private _CCard As2460ocx1;
        public bool isAddSample;

        bool kailustate;//开炉状态

        double[] adchv;//采集电压值

        int[] adch;//采集通道号

        double truePower;
        CMultiPower multipower1;
        double jiareStarttime;
        CPower cpower1;

        int power;//当前功率
        int powertime;
        Cjxtl jx1;
        Cjxtl jx2;
        CjxtlN jxN;
        //int powercount;
        int jxcount;
        bool isPower;
        bool isJx;

        Sig THESIG;//采集线程保存的采集信号

        Thread TH1;//采集线程
        double[] cur = new double[5];
        DemoDbNew demo1;
        ShiXu shixu1;
        System.DateTime startcsydate;
        bool jieqiState=false;
        public bool debugMode;

        bool[] Status = new bool[16];//AD 通道on/off 记录
        bool[] isfirst = new bool[16];
        double startCsyTime;
        //Public islinked As Boolean
        double sig_x;
        double[] y = new double[5];
        //public bool ISRUN;
        public bool isSample;
        //state of csy
        private int State;
        public bool islinked
        {
            get { return As2460ocx1.islinked; }
        }
        public void reset_Renamed()
        {
            //ModMain.isshoudong = false;
            //ModMain.isyuchuli = false;
            ModMain.csystate = csyState.enmReady;
            As2460ocx1.newDA(ModMain.powerChannel, 0);//功率清零  
            isSample = false;
            isJx = false;
        }
        public void shutdown()
        {
            try
            {
                modLog.savelogmsg("class csy shutdown");
                if (!islinked)
                {
                    //gotoState 1
                    //duankai
                }
                else
                {
                    As2460ocx1.shutdown();
                    t1.Enabled = false;
                    t2.Enabled = false;
                    setState(1);
                    this.unLink();
                }
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }
        private void setState(int i)
        {
            State = i;
        }

        public void link()
        {
            if (islinked)
                return;
            try
            {
                As2460ocx1.link();
                if (As2460ocx1.islinked)
                {
                    t1.Interval = 2000;
                    t1.Enabled = true;

                    setState(3);
                    FrameAd.Enabled = true;
                    FrameDo.Enabled = true;
                }
                else
                {
                    if (myErr != null)
                    {
                        myErr(2, null);
                    }
                    //islinked = False
                    setState(0);
                }
                return;
            }
            catch (System.Exception e)
            {
                setState(0);
                //islinked = False
                modLog.savelogmsg("采集卡 init ");
                modLog.savelogmsg(e.ToString());
            }
        }
        public void showopenvlv(vlvindex v)
        {
            //Select Case v
            //    Case vlvindex.总氧
            //        Me.StatusShow.zyf.open()

            //    Case vlvindex.比例阀
            //        Me.StatusShow.blf.close() 'fan
            //    Case vlvindex.反吹
            //        Me.StatusShow.fcf.open()
            //    Case vlvindex.炉后
            //        Me.StatusShow.lhf.open()
            //    Case vlvindex.炉室
            //        Me.StatusShow.lsf.open()
            //    Case vlvindex.排空
            //        Me.StatusShow.pkf.open()
            //    Case vlvindex.升炉
            //        Me.StatusShow.slf.open()
            //    Case vlvindex.氧枪
            //        Me.StatusShow.yqf.open()
            //    Case vlvindex.截止
            //        Me.StatusShow.zzf.open()
            //    Case vlvindex.高频
            //        Me.StatusShow.gaopin(True)
            //    Case vlvindex.刷炉
            //        Me.StatusShow.shualu(True)

            //End Select
            
        }
        public void showclosevlv(vlvindex v)
        {
            //Select Case v
            //    Case vlvindex.总氧
            //        Me.StatusShow.zyf.close()

            //    Case vlvindex.比例阀
            //        Me.StatusShow.blf.open() 'fan
            //    Case vlvindex.反吹
            //        Me.StatusShow.fcf.close()
            //    Case vlvindex.炉后
            //        Me.StatusShow.lhf.close()
            //    Case vlvindex.炉室
            //        Me.StatusShow.lsf.close()
            //    Case vlvindex.排空
            //        Me.StatusShow.pkf.close()
            //    Case vlvindex.升炉
            //        Me.StatusShow.slf.close()

            //    Case vlvindex.氧枪
            //        Me.StatusShow.yqf.close()
            //    Case vlvindex.截止
            //        Me.StatusShow.zzf.close()
            //    Case vlvindex.高频
            //        Me.StatusShow.gaopin(False)
            //    Case vlvindex.刷炉
            //        Me.StatusShow.shualu(False)

            //End Select
            

        }

        public bool openVlv(vlvindex v)
        {
            bool functionReturnValue = false;
            showopenvlv(v);
            functionReturnValue = openVlv2440(ModMain.vlV[(int)v]);
            if ((shixu1 != null))
            {
                shixu1.setdata(As2460ocx1.Byte1, As2460ocx1.Byte1, System.DateTime.Now - startcsydate);
            }
            return functionReturnValue;
        }
        public bool closeVlv(vlvindex v)
        {
            bool functionReturnValue = false;
            showclosevlv(v);
            functionReturnValue = closeVLV2440(ModMain.vlV[(int)v]);
            if ((shixu1 != null))
            {
                shixu1.setdata(As2460ocx1.Byte1, As2460ocx1.Byte1, System.DateTime.Now - startcsydate);
            }
            return functionReturnValue;

        }
        private bool getVlv(vlvindex v)
        {
            return As2460ocx1.getVlv(ModMain.vlV[(int)v]);
        }

        public bool changeCsyState(csyState tostate)
        {
            if (ModMain.csystate != csyState.enmReady)
            {
                return false;
            }
            else
            {
                ModMain.csystate = tostate;
                return true;
            }
        }
        public void startCsy()
        {
            if (tx_gl.isRuning())
            {
                if (myErr != null)
                {
                    myErr(this, new myErrEventArgs(-1, "now is runing task"));
                }
                return;
            }
            //if (ModMain.csystate != csyState.enmReady )
            //{
            //    if (myErr != null)
            //    {
            //        myErr(this, new myErrEventArgs(-1, "not ready!"));
            //    }
            //    return;
            //}
            startcsydate = System.DateTime.Now;
            shixu1 = new ShiXu();
            shixu1.setdata(As2460ocx1.Byte1, As2460ocx1.Byte1, System.DateTime.Now - startcsydate);
            if (State < 1)
            {
                if (myErr != null)
                {
                    myErr(this, new myErrEventArgs(-1, "not ready"));
                }
                return;
            }
            startCsyTime = ModMain.myTimer();
            As2460ocx1.openVLV2440(11);//qiao liu 
            if (ModMain.csystate == Mcsy.csyState.enmSync)
            {
                As2460ocx1.starttime();
                t2.Interval = 10;
                t2.Enabled = true;
                startSample();
                return;
            }
            workQi();
            debugMode = false;
            Check_debug.CheckState = System.Windows.Forms.CheckState.Unchecked;
            //ISRUN = false;
            //Dim suc As Boolean
            if (!islinked)
            {
                //   RaiseEvent myErr(1, "not in state")
                modLog.savelogmsg("please link first");
                //showlog
                if (myErr != null)
                {
                    myErr(this, new myErrEventArgs(-1, "not in state 4"));
                }
                return;
            }
            if (State == 3)
            {
                //close furnace
                if (getVlv((int)vlvindex.enmKailu))
                {
                    //Close
                    closeVlv((vlvindex.enmKailu));
                    //     MySleep 20000 to change
                    if (StatusStr != null)
                    {
                        StatusStr(this, new StatusStrEventArgs(ModMain.gtran.MyTranslate("冲洗", "Purge")));
                    }
                    ModMain.MySleep(15000);
                    closeVlv((vlvindex.enmChongxi));
                }
                //startCsyTime = myTimer()
                As2460ocx1.starttime();

                //if (ModMain.isshoudong)
                if (ModMain.csystate == csyState.enmShoudong)
                {
                    anaLoopShoudong();
                }
                else if (ModMain.csystate == csyState.enmYuchuli)
                {
                    this.anaLoopCuliGanGuo();
                }
                else
                {
                    ModMain.csystate = csyState.enmAuto;
                    anaLoop();
                }
            }
            return;
        }
        public void anaLoop()
        {
            //debugpid = False
            if (StatusStr != null)
            {
                StatusStr(this, new StatusStrEventArgs(ModMain.gtran.MyTranslate("脱气开始", "OutGas")));
            }
            openVlv((vlvindex.enmChongxi));
            t2.Interval = 10;
            power = ModMain.method1.tuoqiPower;
            //tuoqipower
            powertime = (int)(ModMain.method1.tuoqiTime + ModMain.method1.flushtime + ModMain.method1.dengdaitime + 1.8 + multipower1.totalTime);
            //powercount = 0;
            isPower = true;

            cpower1.InitialPID(power);
            isJx = true;
            //jx1.InitialPID(0)
            //jx2.InitialPID(0)
            //jxN.InitialPID(0)

            t2_Tick(t2, new System.EventArgs());
            //
            t2.Enabled = true;
            //todo
            tx_gl.addOneTaskBy(4, 0, ModMain.method1.tuoqiTime, (TimerExt3.myAction)task4, null);
            tx_gl.addOneTaskBy(5, 4, ModMain.method1.flushtime, task5, null);
            tx_gl.addOneTaskBy(6, 5, ModMain.method1.dengdaitime, task6, null);
            tx_gl.addOneTaskBy(8, 6, 1, task8, null);
            //touyang
            tx_gl.addOneTaskBy(16, 8, ModMain.method1.sample_delay, task16, null);
            tx_gl.addOneTaskBy(17, 16, ModMain.method1.sampletime, task17, null);
            tx_gl.start();
            if (startTask != null)
            {
                startTask(this, new startTaskEventArgs(1));
            }
            //auto ana
        }
        public void task4(List<Cmd> i)
        {
            setState(4);
            modLog.savelogmsg("change power");
            power = ModMain.method1.chongxi_power;
            if (StatusStr != null)
            {
                StatusStr(this, new StatusStrEventArgs(ModMain.gtran.MyTranslate("冲洗开始", "Purge")));
            }
            //脱气结束
        }
        public void task5(List<Cmd> i)
        {
            closeVlv((vlvindex.enmChongxi));
            power = ModMain.method1.dengdai_power;
            setState(5);
            if (StatusStr != null)
            {
                StatusStr(this, new StatusStrEventArgs(ModMain.gtran.MyTranslate("等待", "Wait")));
            }
        }
        public void task6(List<Cmd> i)
        {
            isJx = false;
            openVlv((vlvindex.enmTouyang));
            if (StatusStr != null)
            {
                StatusStr(this, new StatusStrEventArgs(ModMain.gtran.MyTranslate("投样1", "Drop")));
            }
            setState(6);
        }
        public void task7(List<Cmd> i)
        {
            isJx = false;
            setState(7);
            //debugpid = False
            t2.Interval = 10;
            power = ModMain.method1.tuoqiPower;
            powertime = (int)multipower1.totalTime;
            //powercount = 0;
            isPower = true;
            //startCsyTime = myTimer()
            As2460ocx1.starttime();
            jiareStarttime = ModMain.myTimer();
            //    If method1.multiPower Then
            multipower1.beginPower();
            //    Else
            //    End If
            cpower1.InitialPID(power);
            startSample();
            t2_Tick(t2, new System.EventArgs());
            //
            t2.Enabled = true;
            if (StatusStr != null)
            {
                StatusStr(this, new StatusStrEventArgs(ModMain.gtran.MyTranslate("加热", "Ana.Power")));
            }
        }
        //Function calctotalTime(ByVal m As NCS.method)
        //    Return 0
        //End Function
        public void task8(List<Cmd> i)
        {
            closeVlv((vlvindex.enmTouyang));
            jiareStarttime = ModMain.myTimer();
            multipower1.beginPower();
            setState(8);
        }
        public void task14(List<Cmd> i)
        {
            openVlv((vlvindex.enmTouyang));
            if (StatusStr != null)
            {
                StatusStr(this, new StatusStrEventArgs(ModMain.gtran.MyTranslate("投样1", "Drop")));
            }
        }
        public void task15(List<Cmd> i)
        {
            State = 3;
            //ModMain.isyuchuli = false;
            ModMain.csystate = csyState.enmReady;
            t2.Enabled = false;
            if (evReset != null)
            {
                evReset(this, null);
            }
        }
        public void task16(List<Cmd> i)
        {
            State = 16;
            startSample();
            if (StatusStr != null)
            {
                StatusStr(this, new StatusStrEventArgs(ModMain.gtran.MyTranslate("分析", "Analysis")));
            }
        }
        public void task17(List<Cmd> i)
        {
            if (StatusStr != null)
            {
                StatusStr(this, new StatusStrEventArgs(ModMain.gtran.MyTranslate("结束", "Ready")));
            }
            //     setState 9
            stopSample();
            //As2460ocx1.NZero
            //Call tiaoling
            if (!islinked)
            {
                link();
            }
            if (islinked)
            {
                setState(3);
            }
            //ModMain.isshoudong = false;
            ModMain.csystate = csyState.enmReady;
        }
        public void anaLoopCuliGanGuo()
        {
            //debugpid = False
            openVlv((vlvindex.enmChongxi));
            t2.Interval = 10;
            power = ModMain.method1.tuoqiPower;
            powertime = ModMain.method1.tuoqiTime;
            //+ congxitime
            //powercount = 0;
            isPower = true;
            cpower1.InitialPID(power);
            //   isJx = True
            //   jx1.InitialPID 0
            //   jx2.InitialPID 0
            //   jxN.InitialPID 0

            t2_Tick(t2, new System.EventArgs());
            //
            t2.Enabled = true;
            tx_gl.addOneTaskBy(4, 0, ModMain.method1.tuoqiTime, task4, null);
            //MySleep tuoqitime
            tx_gl.addOneTaskBy(5, 4, ModMain.method1.flushtime, task5, null);
            tx_gl.addOneTaskBy(15, 5, 10, task15, null);
            tx_gl.start();
            if (startTask != null)
            {
                startTask(this, new startTaskEventArgs(4));
            }
            //auto ana
        }
        public void anaLoopShoudong()
        {
            //savelogmsg "deng dai "
            //MySleep dengdaitime * 1000
            isJx = true;
            //jx1.InitialPID(0)
            //jx2.InitialPID(0)
            //jxN.InitialPID(0)

            t2_Tick(t2, new System.EventArgs());
            //
            t2.Enabled = true;
            //If method1.multiPower Then
            powertime = (int)(ModMain.method1.tuoqiTime + ModMain.method1.flushtime + ModMain.method1.dengdaitime + 3 + 0 + multipower1.totalTime);
            //Else
            //powertime = tuoqitime + congxitime + dengdaitime + 3 + 0 + jiaretime
            ////End If
            tx_gl.addOneTaskBy(7, 0, ModMain.method1.dengdaitime, task7, null);
            //    tx_gl.addOneTaskBy 8, 7, 3
            tx_gl.addOneTaskBy(17, 7, ModMain.method1.sampletime, task17, null);
            tx_gl.start();
            if (startTask != null)
            {
                startTask(this, new startTaskEventArgs(7));
            }
            //auto ana
        }

        public int newshixuid()
        {
            Db4objects.Db4o.IObjectContainer db = null;
            db = Db4objects.Db4o.Db4oFactory.OpenFile(modLog.initpath + "\\shixu.data");
            Db4objects.Db4o.Query.IQuery query = db.Query();
            query.Constrain(typeof(ShixuId));
            Db4objects.Db4o.IObjectSet o = null;
            o = query.Execute();
            ShixuId m = null;
            if (o.Count > 0)
            {
                m = (ShixuId)o[0];
            }
            else
            {
                m = new ShixuId();
                m.id = 0;
            }
            m.id = m.id + 1;
            //db.Set(m);
            db.Close();
            return m.id;
        }
        public void dbrecordshixu(ref ShiXu s1)
        {
            s1.id = newshixuid();
            Db4objects.Db4o.IObjectContainer db = null;
            db = Db4objects.Db4o.Db4oFactory.OpenFile(modLog.initpath + "\\shixu.data");
            //db.Set(s1);
            db.Close();

        }

        public void stopCsy()
        {
            //if (ModMain.SYNC) {
            //    stopSample();
            //    return;
            //}

            //tx_fx.clearTasks()
            //fxreset()
            //stopSample();
            //setState(3);
            try
            {
                switch (ModMain.csystate)
                {
                    case csyState.enmSync:
                        stopSample();
                        break;
                    case csyState.enmYuchuli:
                        cpower1.StopPID();
                        switch (State)
                        {
                            case 3:
                                this.closeVlv(vlvindex.enmChongxi);
                                t2.Enabled = false;
                                break;
                            case 4:
                                this.closeVlv((vlvindex.enmChongxi));
                                t2.Enabled = false;
                                break;
                            case 5:
                                t2.Enabled = false;
                                break;
                            //case default :
                            //    ;
                            //    //savelogmsg("stop yuchuli :" & Str(State))
                        }
                        break;
                    case csyState.enmAddSample:
                        this.closeVlv((vlvindex.enmJiayang));
                        this.closeVlv((vlvindex.enmChongxi));
                        this.closeVlv((vlvindex.enmFengding));
                        break;
                    case csyState.enmAuto:
                        switch (State)
                        {
                            case 3:
                            case 4:
                            case 5:
                            case 6:
                            case 7:
                            case 8:
                                cpower1.StopPID();
                                closeVlv((vlvindex.enmChongxi));
                                closeVlv((vlvindex.enmFengding));
                                closeVlv((vlvindex.enmJiayang));
                                closeVlv((vlvindex.enmKailu));
                                closeVlv((vlvindex.enmTouyang));
                                break;
                            case 16:
                                cpower1.StopPID();
                                stopSample();
                                closeVlv((vlvindex.enmChongxi));
                                closeVlv((vlvindex.enmFengding));
                                closeVlv((vlvindex.enmJiayang));
                                closeVlv((vlvindex.enmKailu));
                                closeVlv((vlvindex.enmTouyang));
                                break;
                        }
                        break;

                }
                ModMain.csystate = csyState.enmReady;
                setState(3);

                t1.Enabled = false;
                tx_gl.clearTasks();
                startCsyTime = 0;

            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
                //RaiseEvent myErr(Me, New myErrEventArgs(Err.Number, Err.Description))    
            }
        }

        //UPGRADE_WARNING: Event Check1.CheckStateChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSExpressCC.v80/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'

        private void Check1_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
        {
        }

        //UPGRADE_WARNING: Event Check2.CheckStateChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSExpressCC.v80/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'

        private void Check2_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
        {
        }




        private void Command3_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            refreshVlvState();
        }
        public void refreshVlvState()
        {
            //Dim at As int
            int i = 0;
            bool b = false;
            List_do.Items.Clear();
            for (i = 0; i <= 16 - 1; i++)
            {
                b = getBit(i);
                if (b)
                {
                    list1Additem(i, true);
                }
                else
                {
                    list1Additem(i, false);
                }
            }
        }

        //change2005-12-29
        private void Command4_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //gpTime = Val(Text2.Text)
            //Text2.Text = cstr(gpTime)
            //sampletime = Val(Text3.Text)
            //Text3.Text = cstr(sampletime)
            //flushtime = Val(Text6.Text)
            //Text6.Text = cstr(flushtime)
            //'***********
            //Command4.Enabled = False
            //Text2.Enabled = False
        }

        private void Msample1_dataReceive(ref double x, ref double y, ref int i)
        {
            if (dataReceive != null)
            {
                dataReceive(this, new dataReceiveEventArgs(x, y, i));
            }
        }

        private void Command5_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            Command_da.Enabled = false;
            //UPGRADE_NOTE: chanel was upgraded to chanel_Renamed. Click for more: 'ms-help://MS.VSExpressCC.v80/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"'
            int chanel_Renamed = 0;
            double v = 0;
            chanel_Renamed = (int)Conversion.Val(Text_da.Text);
            v = Conversion.Val(Text_da_out.Text);
            As2460ocx1.newDA(chanel_Renamed, v);
            Command_da.Enabled = true;
        }

        private void Command6_Click()
        {
            //Text2.Enabled = True

        }
        public void backState(int i)
        {
            //savelogmsg("backstate" + CStr[i])
            //Select Case i
            //    Case 4 '5 to 4
            //        Call closeVlv((vlvindex.升炉)) '开炉
            //        MySleep(3000)
            //        Call openVlv((vlvindex.刷炉)) '
            //        MySleep(3000)
            //        Call closeVlv((vlvindex.刷炉)) '
            //        setState[i]
            //    Case 3 '4 to 3
            //        Call closeVlv((vlvindex.刷炉)) '
            //        MySleep(3000)
            //        Call openVlv((vlvindex.升炉))
            //        setState[i]
            //    Case 2 '3 to 2
            //        Call closeVlv((vlvindex.旁路))
            //        Call closeVlv((vlvindex.总氧))
            //        setState[i]
            //    Case 1 '断开高频电源 '2 to 1
            //        Call closeVlv((vlvindex.高频电源))
            //        setState[i]
            //    Case 0 '断开联机  '1 to 0
            //        unLink()
            //        If Not islinked Then
            //            FrameAd.Enabled = False
            //            FrameDo.Enabled = False
            //            setState[i]
            //        End If
            //End Select
        }

        public bool gotoState(ref int i)
        {
            return true;
            //    Dim res As Boolean
            //    res = True
            //    savelogmsg("goto state" + CStr[i])
            //    Dim usetime As Single
            //    Select Case i
            //        Case 1 '0 to 1
            //            link()
            //            If islinked Then
            //                setState[i]
            //            End If
            //        Case 2
            //            Call openVlv((vlvindex.高频电源)) '高频电源
            //            tGp.Interval = 1000 '*5*60=5 minute
            //            t2number = 0
            //            tstate = timerState.enmGpPower
            //            tGp.Enabled = True
            //        Case 3 '
            //            Call openVlv((vlvindex.总氧))
            //            If getdi((diIndex.enmZongyang)) Then
            //                If getdi((diIndex.enmDongli]) Then
            //                    Me.StatusShow.youqi = True
            //                    Call openVlv((vlvindex.炉后))
            //                    setState[i]
            //                Else
            //                    Me.StatusShow.youqi = False
            //                    closeVlv((vlvindex.总氧))
            //                    savelogmsg("动力压力不正常！")
            //                    curErr = -3
            //                    res = False
            //                End If
            //            Else
            //                closeVlv((vlvindex.总氧))
            //                curErr = -3
            //                savelogmsg("总氧压力不正常！")
            //                res = False
            //            End If
            //        Case 4
            //            '   Timer1.Interval = 0
            //            setState[i]


            //        Case 5

            //            If jieqiState Then
            //                jieqiState = False
            //            End If
            //            '    Call openVlv(vlvindex.enmShengJiang) '关炉
            //            '    Call closeVlv(vlvindex.enmLLTJ)
            //            '    Call openVlv(vlvindex.enmHuancui]  'huancui
            //            '    Call openVlv(vlvindex.enmPaikong)
            //            '    Call openVlv(vlvindex.enmLushi]
            //            '    mysleep 4500 'wait
            //            '*************************************************
            //            Call openVlv(vlvindex.总氧)
            //            Call openVlv(vlvindex.升炉) '关炉
            //            Call openVlv(vlvindex.排空) '
            //            Call openVlv((vlvindex.吸尘))
            //            Call openVlv((vlvindex.炉室))
            //            Call openVlv(vlvindex.炉后)
            //            Call openVlv((vlvindex.氧枪))
            //            Call openVlv(vlvindex.反吹) 'huancui
            //            MySleep(1000) '
            //            Call closeVlv(vlvindex.氧枪)
            //            Call closeVlv(vlvindex.反吹)

            //            If checkshenglu() Then
            //                '           myDelay (1.2)
            //                '        '   mysleep 1200
            //                Call closeVlv((vlvindex.吸尘))
            //                Call openVlv(vlvindex.比例阀) '开
            //                Call closeVlv(vlvindex.排空)
            //                '
            //                ''*************************************************
            //                setState[i]
            //            Else
            //                Call closeVlv(vlvindex.总氧)
            //                Call closeVlv(vlvindex.升炉) '关炉
            //                Call closeVlv(vlvindex.排空) '
            //                Call closeVlv((vlvindex.吸尘))
            //                Call closeVlv((vlvindex.炉室))
            //                curErr = -5
            //                res = False
            //            End If

            //        Case 6

            //            'Call closeVlv((vlvindex.enmHuancui]) 'huancui
            //            'Call closeVlv((vlvindex.enmPaikong))
            //            'Call openVlv((vlvindex.enmLuhou))
            //            'If checkluhou() Then
            //            '    setState[i]
            //            'Else
            //            '    '        setState 4
            //            '    Call closeVlv((vlvindex.enmLuhou))
            //            '    curErr = -6
            //            '    res = False
            //            'End If
            //            setState[i]
            //            res = True
            //        Case 7
            //            setState[i]
            //        Case 8
            //            savelogmsg(("start gaopin"))
            //            Me.tiaozhengBase(usetime)
            //            MySleep(flushtime * 1000 - usetime * 1000) 'tiaozhengbase use time 10 second
            //            Call openVlv((vlvindex.高频))
            //            MySleep(1000)
            //            Call openVlv((vlvindex.氧枪))
            //            MySleep(1000)
            //            '
            //            Call closeVlv((vlvindex.炉室))
            //            tSample.Interval = method1.powertime * 1000
            //            tSample.Enabled = True
            //            'startSample()
            //            'TH1 = New Thread(New ThreadStart(AddressOf Me.startSample))
            //            'TH1.Start()
            //            'Do While TH1.IsAlive
            //            '    System.Windows.Forms.Application.DoEvents()
            //            'Loop
            //            startSample()
            //        Case 9
            //            tSample.Enabled = False
            //            Call closeVlv((vlvindex.高频))
            //            setState[i]
            //        Case 10
            //            'If Not debugMode Then
            //            savelogmsg("begin event finish")
            //            stopSample()
            //            savelogmsg("end event finish")
            //            'End If

            //            setState[i]
            //        Case 11
            //            closeVlv((vlvindex.氧枪))
            //            closeVlv((vlvindex.比例阀)) '关
            //            closeVlv((vlvindex.截止)) '关
            //            openVlv((vlvindex.吸尘))
            //            openVlv((vlvindex.排空))
            //            MySleep(2000)
            //            Call closeVlv((vlvindex.升炉)) '开炉
            //            Call closeVlv((vlvindex.排空))
            //            Call openVlv((vlvindex.反吹)) 'huancui
            //            'mysleep(2000)
            //            MySleep(2000)
            //            Call openVlv((vlvindex.刷炉))
            //            MySleep(2000)
            //            Call closeVlv((vlvindex.刷炉))
            //            MySleep(1000)
            //            Call closeVlv((vlvindex.反吹)) 'huancui
            //            closeVlv((vlvindex.炉后))
            //            Call closeVlv(vlvindex.吸尘)
            //            Call closeVlv(vlvindex.总氧)
            //            setState[i]
            //    End Select
            //    gotoState = res
            //End Function

            //Private Sub t1_Tick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles tGp.Tick '多用途时钟
            //    t2number = t2number + 1
            //    RaiseEvent myGp(Me, New myGpEventArgs(5 * 60 - t2number, "left"))
            //    'savelogmsg "还有" + cstr((5 * 60 - t2number) / 60#) + "分钟"
            //    If t2number = 5 * 60 Then
            //        tGp.Enabled = False
            //        setState(2)
            //    End If
        }
        //Private Sub startGP()
        //    savelogmsg(("start gaopin"))
        //    '判断零值稳定
        //    isStable()
        //    '开高频
        //    'comm1.Output = Chr(11)
        //    Dim usetime As Single
        //    Debug.Print("============flush time")
        //    Debug.Print(myTimer)
        //    Me.tiaozhengBase(usetime)
        //    Debug.Print(myTimer)
        //    mysleep(flushtime * 1000 - usetime * 1000) 'tiaozhengbase use time 10 second
        //    Call openVlv((vlvindex.enmGaoPin))
        //    Call openVlv((vlvindex.enmYangqiang))
        //    mysleep(1000)
        //    '
        //    Call closeVlv((vlvindex.enmLushi])
        //    'UPGRADE_WARNING: Timer property t2.Interval cannot have a value of 0. Click for more: 'ms-help://MS.VSExpressCC.v80/dv_commoner/local/redirect.htm?keyword="169ECF4A-1968-402D-B243-16603CC08604"'
        //    t2.Interval = gpTime * 1000
        //    t2.Enabled = True
        //    setState(7)
        //    If Not debugMode Then
        //        startSample()
        //    End If
        //End Sub
        //private void stopGP()
        //{
        //    modLog.savelogmsg(("stop gaopin"));
        //    //判断零值稳定
        //    isStable();
        //    //开高频
        //    //comm1.Output = Chr(11)
        //    closeVlv(vlvindex.);
        //}


        private void isStable()
        {
        }
        //public double getPresure()
        //{
        //    //  saveLogmsg ("get presure")
        //    //  getPresure = mcom1.getPresure
        //    //  Call mysend    'qu yali
        //}

        private void t2_Tick(System.Object eventSender, System.EventArgs eventArgs)
        {
            double tmp = 0;
            sig_x = ModMain.myTimer() - startCsyTime;
            double truev = 0;
            double truec = 0;
            if (isPower)
            {
                if ((ModMain.myTimer() - startCsyTime) > powertime)
                {
                    isPower = false;
                    cpower1.StopPID();
                }
                else
                {
                    if (State >= 7)
                    {
                        power = (int)multipower1.getPower();
                        //not change power
                    }
                    else
                    {
                    }
                    truePower = cpower1.PID(0, power, ref truev, ref truec);
                    if (EVpower != null)
                    {
                        EVpower(this, new EVpowerEventArgs(sig_x, truePower));
                    }
                }
            }
            if (isSample)
            {
                As2460ocx1.getchanelsVolts(ref adch, ref adchv, ModMain.NUMChanel, ref tmp);
                if (adchv[0] > 9.999)
                {
                    if (dataEnd != null)
                    {
                        dataEnd(this, new dataEndEventArgs(0));
                    }
                }
                if (adchv[1] > 9.999)
                {
                    if (dataEnd != null)
                    {
                        dataEnd(this, new dataEndEventArgs(1));
                    }
                }
                if (dataReceiveMulti != null)
                {
                    dataReceiveMulti(this, new dataReceiveMultiEventArgs(sig_x, adchv, ModMain.NUMChanel));
                }
            }
            if (isJx)
            {
                jxcount = jxcount + 1;
                //500ms
                if (jxcount == 500 / 10)
                {
                    jx1.PID(0);
                    jx2.PID(0);
                    jxcount = 0;
                }
                jxN.PID(0);
                //采用累加平均减小噪声影响
            }

        }

        //Public Sub setTimePara(ByRef startCsyTime As int, ByRef ftime As int)
        //    sampletime = startCsyTime
        //    flushtime = ftime
        //    multipower1.loadPara()
        //End Sub

        //Private Sub Timer1_Tick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
        //    Timer1.Interval = 500
        //    Timer1.Tag = 1
        //    gotoState(11)
        //    Timer1.Enabled = False
        //End Sub





        private void UserControl_Initialize()
        {
            //cd = New ChanelDic
            adch = new int[ModMain.NUMChanel];
            this.adchv = new double[ModMain.NUMChanel];
            tx_gl = new TimerExt3();
            //tx_cksl = New tmExt2.TimerExt3(Me.t1)
            //tx_fx = New tmExt2.TimerExt3()
            cpower1 = new CPower();
            demo1 = new DemoDbNew();
            multipower1 = new CMultiPower();
            //recordshixu = True
            As2460ocx1 = new CCardComboPci();
            cpower1.setCard(ref As2460ocx1);
            jx1 = new Cjxtl();
            jx2 = new Cjxtl();
            jxN = new CjxtlN();
            jx1.setCard(ref As2460ocx1);
            jx2.setCard(ref As2460ocx1);
            jxN.setCard(ref As2460ocx1);
            //shualueach = True
            debugMode = false;
            //nstat = 12
            //Dim statStr(12) As String
            //statStr(0) = "未连接"
            //statStr(1) = "已连接"
            //statStr(2) = "开氧气旁路阀"
            //statStr(3) = "开炉(关升降阀)"
            //statStr(4) = "关炉(开升降阀)"
            //statStr(5) = "开炉室,开排空关排空"
            //statStr(6) = "关旁路,开炉后"
            //statStr(7) = "开高频开氧枪采样"
            //statStr(8) = "关高频"
            //statStr(9) = "关炉后,开旁路,关氧枪,关炉室"
            //statStr(10) = "开排空关排空"
            //statStr(11) = "开高频电源"
            //ReDim stat(nstat - 1)
            int i = 0;
            //For i = 0 To 1 'nstat - 1
            //    stat[i] = statStr[i]
            //Next i
            //stat(2) = statStr(11)
            //For i = 3 To nstat - 1
            //    stat[i] = statStr(i - 1)
            //Next i
            //MStatus1.setNStatus(stat, nstat)
            State = 0;
            //MStatus1.setStatus(State)
            // Call getvlvset
            //Dim i As Integer
            mcurve1.setLineCount(16);
            mcurve1.setxyDw("S", "V");
            mcurve1.setscale(0, 0, 40, 10);
            Color[] colors = null;
            colors = new Color[16];

            for (i = 0; i <= 15; i++)
            {
                //colors[i] = Color.FromArgb(Math.Pow(2, 31) / 17 * (i + 1));
                mcurve1.setlinecolor(i, colors[i]);
            }
            mcurve1.draw();

            //Combo1.Items.Add("±5V")
            //Combo1.Items.Add("±10V")
            //Combo1.Items.Add("±3.3V")
            //Combo1.Items.Add("-15 to 5V")
            //Combo1.Items.Add("0.833 to 7.5V")
            //Combo1.Items.Add(" -2.5 to 17.5V")
            //Combo1.Items.Add(" 2.5 to 22.5V")
            //Combo1.Items.Add(" 0 to 2.857V")
            //Combo1.Items.Add(" -1 to 3V")
            //Combo1.Items.Add(" 0 to 4V")
            //Combo1.Items.Add(" -6.25 to 3.75V")
            //Combo1.Items.Add(" 0 to 10V")
            //Combo1.Items.Add(" 0.375 to 3.214V")
            //Combo1.Items.Add(" -0.5 to 3.5V")
            //Combo1.Items.Add(" 0.5 to 4.5V")
            //Combo1.Items.Add(" 1.25 to 11.25V") 'Call Mcurve1.setLineCount(16)
            //Combo1.SelectedIndex = 11
            //Combo1.Enabled = False
            for (i = 0; i <= 15; i++)
            {
                List_ad.Items.Insert(i, Convert.ToString(i) + "off");
            }
            //For i = 0 To 15
            //    ChannelOn[i] = False
            //Next
            for (i = 0; i <= 15; i++)
            {
                Status[i] = false;
            }
            FrameAd.Enabled = false;
            FrameDo.Enabled = false;
            //NewStart = True
            //Active = False
            tx_gl.endAllTask += tx_gl_endAllTask;
            this.Text_da.Items.Add(0);
            this.Text_da.Items.Add(1);
            this.Text_da.Items.Add(2);
            this.Text_da.Items.Add(3);
            this.Text_da.Items.Add(4);
            this.Text_da.Items.Add(5);
            this.Text_da.Items.Add(6);
            this.Text_da.Items.Add(7);
            this.Text_da.Items.Add(8);

        }

        public void list1Additem(int i, bool b)
        {
            int at = 0;
            bool find = false;
            at = ModMain.inArrNew(i, ModMain.vlV, ModMain.nvlv, ref find);
            if (find)
            {
                if (b)
                {
                    List_do.Items.Insert(i, ModMain.vlvName[at] + " " + "ON");
                }
                else
                {
                    List_do.Items.Insert(i, ModMain.vlvName[at] + " " + "OFF");
                }
            }
            else
            {
                if (b)
                {
                    List_do.Items.Insert(i, Convert.ToString(i) + " " + "ON");
                }
                else
                {
                    List_do.Items.Insert(i, Convert.ToString(i) + " " + "OFF");
                }
            }

        }

        public bool openVlv2440(int v)
        {
            return As2460ocx1.openVLV2440(v);
        }
        public bool closeVLV2440(int v)
        {
            return As2460ocx1.closeVLV2440(v);
        }

        public bool getBit(int i)
        {
            return As2460ocx1.getVlv(i);
        }

        public void unLink()
        {
            try
            {
                As2460ocx1.unLink();
                //islinked = False
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
                //islinked = True
            }
        }
        private void SAMPLE()
        {
            double sx = 0;
            double[] sy = new double[5];
            THESIG = new Sig();
            int I = 0;
            double beginSampletime = 0;
            beginSampletime = ModMain.myTimer();
            while (isSample)
            {
                sx = ModMain.timeGetTime() / 1000.0F - startCsyTime;
                //CDbl(Now()) - stime
                if (ModMain.program1.demo)
                {
                    sy[0] = new System.Random().NextDouble();//..Rnd();
                }
                else
                {
                    sy[0] = As2460ocx1.getchanelVolt(ModMain.getEleChanel("C"));
                }
                //if (sy[0] > ModMain.method1.cswitch) {
                //    if (dataEnd != null) {
                //        dataEnd(this, new dataEndEventArgs(0));
                //    }
                //}
                if (ModMain.program1.demo)
                {
                    sy[1] = new System.Random().NextDouble();
                }
                else
                {
                    sy[1] = As2460ocx1.getchanelVolt(ModMain.getEleChanel("S"));
                }

                //if (sy[1] > ModMain.method1.sswitch) {
                //    if (dataEnd != null) {
                //        dataEnd(this, new dataEndEventArgs(1));
                //    }
                //}
                if (!ModMain.program1.demo)
                {
                    sy[2] = As2460ocx1.getchanelVolt(ModMain.getEleChanel("C2"));
                    //'chanel
                    sy[3] = As2460ocx1.getchanelVolt(ModMain.getEleChanel("S2"));
                    //'chanel
                }
                else
                {
                    sy[2] = new System.Random().NextDouble();
                    sy[3] = new System.Random().NextDouble();
                }
                THESIG.setPoint(sx, THESIG.xn);
                for (I = 0; I <= ModMain.NUMChanel - 1; I++)
                {
                    THESIG.setPoint(sy[I], Convert.ToString(I), THESIG.xn);
                }
                THESIG.xn = THESIG.xn + 1;
                Thread.Sleep(6);
                if (ModMain.csystate == Mcsy.csyState.enmSync)
                {
                }
                else
                {
                    if (ModMain.myTimer() - beginSampletime > ModMain.method1.sampletime)
                        isSample = false;
                }
            }
        }

        public void stopSample()
        {
            t2.Enabled = false;
            cpower1.StopPID();
            isSample = false;
            isPower = false;
            if (TH1 == null)
            {
            }
            else
            {
                if (TH1.IsAlive)
                {
                    TH1.Abort();
                }
                if (FinishSIG != null)
                {
                    FinishSIG(this, new sigFinishEventArgs(THESIG));
                }
            }
        }
        public void startSample()
        {
            isSample = true;
            TH1 = new Thread(new ThreadStart(this.SAMPLE));
            //真正采集数据
            //TH1.Priority = ThreadPriority.Highest
            TH1.Start();

            //下面的采集用于界面显示
            t2.Enabled = true;
            t2.Interval = 10;
            //initFinishBool()
            //startCsyTime = timeGetTime() / 1000.0#
        }

        public void tiaozhengBase1(ref double timeUsed)
        {
            if (State < 1)
            {
                modLog.savelogmsg("not in state");
                return;
            }
            else
            {
            }
            int i = 0;
            int[] c = new int[5];
            double[] usetime = new double[5];
            c[1] = ModMain.getEleChanel("C");
            c[2] = ModMain.getEleChanel("S");
            c[3] = ModMain.getEleChanel("C2");
            c[4] = ModMain.getEleChanel("S2");
            for (i = 1; i <= 4; i++)
            {
                tiaozhengOne1(ref c[i], ref usetime[i]);
            }
        }
        public double changeJixian(int i, double cur, int get)
        {
            //Debug.Print(ModMain.myTimer());
            As2460ocx1.newDA(i, cur);
            Thread.Sleep(400);
            //Debug.Print(ModMain.myTimer());
            return getVolt(get);
        }
        //by binSearch
        public void tiaozhengOne1(ref int i, ref double usetime)
        {
            double cur = 0;
            double up = 0;
            double down = 0;
            //nst'
            double des = 0;
            des = 0.0F;
            double derr = 0;
            derr = 0.1F;
            double cup = 0;
            double cld = 0;
            double ccurv = 0;
            cup = 10;
            cld = -10;
            ccurv = 0;
            //'
            cur = ccurv;
            up = cup;
            down = cld;
            double y = 0;
            //Dim Y2 As double
            double t = 0;
            t = ModMain.myTimer();
            while (ModMain.timePasted(t) < 3)
            {
                As2460ocx1.newDA(i, cur);
                Thread.Sleep(400);
                y = getVolt(i);
                Debug.Print(Convert.ToString(i) + "," + Convert.ToString(cur) + "," + Convert.ToString(y) + "," + Convert.ToString(up) + "," + Convert.ToString(down));
                if (System.Math.Abs(y - des) < derr)
                    return;
                if (y > des)
                {
                    if (System.Math.Abs(cur - cld) <= 20 / 32767)
                        return;
                    up = cur;
                    //-
                    cur = (up + down) / 2;
                }
                else if (y < des)
                {
                    down = cur;
                    //+
                    if (System.Math.Abs(cur - cup) <= 20 / 32767)
                        return;
                    cur = (up + down) / 2;
                }
            }
            usetime = ModMain.myTimer() - t;
        }

        public void tiaozhengOne(ref int i)
        {
            double y = 0;
            double Y2 = 0;
            y = getVolt(i);
            if (y < 0.01 & y > 0.03)
            {
                As2460ocx1.newDA(i, 0);
                y = getVolt(i);
                As2460ocx1.newDA(i, 4095);
                Y2 = getVolt(i);
                if (inrange(y, Y2, 0.02F))
                {
                    As2460ocx1.newDA(i, (0.02F - y) / (Y2 - y) + y);
                    y = getVolt(i);
                }
                else
                {
                }
            }
        }
        //
        public bool inrange(double min, double max, double x)
        {
            bool functionReturnValue = false;
            double tmp = 0;
            if (min >= max)
            {
                tmp = min;
                min = max;
                max = tmp;
            }
            if (x >= min & x <= max)
            {
                functionReturnValue = true;
            }
            else
            {
                functionReturnValue = false;
            }
            return functionReturnValue;
        }
        public void displaychn(ref string[] v_vlvName, ref int v_nvlv)
        {
            try
            {
                //Dim at As int
                //Dim find As Boolean
                List_ad.Items.Clear();
                int i = 0;
                //ReDim ss(15)
                //
                for (i = 0; i <= 15; i++)
                {
                    List_ad.Items.Insert(i, v_vlvName[i] + " " + "OFF");
                }
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }

        public double getVolt(int i)
        {
            return As2460ocx1.getchanelVolt(i);
            //'chanel
        }

        public void setvlv()
        {
            try
            {
                //nvlv = v_nvlv
                //ReDim vlV(nvlv)
                //ReDim vlvName(nvlv)
                int i = 0;
                //For i = 0 To nvlv - 1
                //    vlV[i] = v_vlV[i]
                //    vlvName[i] = v_vlvName[i]
                //Next i
                int at = 0;
                bool find = false;
                List_do.Items.Clear();
                //Dim i As Integer
                //
                for (i = 0; i <= 15; i++)
                {
                    at = ModMain.inArrNew(Convert.ToInt32(i), ModMain.vlV, ModMain.nvlv, ref find);
                    if (find)
                    {
                        List_do.Items.Insert(i, ModMain.vlvName[at] + " " + "OFF");
                    }
                    else
                    {
                        List_do.Items.Insert(i, Convert.ToString(i) + " " + "OFF");
                    }
                }
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }
        public void jieqi()
        {
            closeVlv(vlvindex.enmBili);
            jieqiState = true;
            if (EVjieQi != null)
            {
                this.EVjieQi(this, new StatusJieQiEventArgs(jieqiState));
            }
        }
        public void closeGp()
        {
            this.reset_Renamed();
            backState(1);
        }
        //Public Sub setDi(ByRef v_vlV() As int, ByRef v_vlvName() As String, ByRef v_nvlv As int)
        //    Try
        //        nDi = v_nvlv
        //        ReDim dichanel(nDi]
        //        ReDim diName(nDi]
        //        Dim i As int
        //        For i = 0 To nDi - 1
        //            dichanel[i] = v_vlV[i]
        //            diName[i] = v_vlvName[i]
        //        Next i
        //        'Call mstatusv1.setNStatus(diName, nDi]
        //        Exit Sub
        //    Catch e As System.Exception
        //        saveerrmsg()
        //    End Try
        //End Sub

        public bool getdi(diIndex i)
        {
            //As2460ocx1.getdi(dichanel[i])
            return true;
        }
        public bool checkshenglu()
        {
            if (ModMain.program1.demo)
            {
                ModMain.MySleep(3000);
                return true;
            }
            double stime = 0;
            stime = ModMain.myTimer();
            bool res = false;
            res = true;
            do
            {
                if (getdi((diIndex.enmShenglu)))
                {
                    break;
                }

                if (ModMain.timePasted(stime) > 5)
                {
                    res = false;
                    modLog.savelogmsg("升炉不到位！");
                    break;
                }
            } while ((true));
            return res;
        }
        public bool checkluhou()
        {
            double stime = 0;
            stime = ModMain.myTimer();
            bool res = false;
            res = true;
            do
            {
                if (getdi((diIndex.enmLuhou)))
                {
                    break;
                }

                if (ModMain.timePasted(stime) > 5)
                {
                    res = false;
                    modLog.savelogmsg("炉后氧压低！");
                    break;
                }
            } while ((true));
            return res;
        }

        private void List1_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (!debugMode)
                return;
            int i = 0;
            bool b = false;
            List_do.Enabled = false;
            i = List_do.SelectedIndex;
            if (i == -1)
                return;
            b = getBit(i);
            if (b)
            {
                // to off
                closevlvfromlist(i);
                List_do.Items.RemoveAt(i);
                list1Additem(i, false);

            }
            else
            {
                // to on
                //can not stargp when shualu on
                //if (i == 4 & getBit( 0)) {
                //    if (myErr != null) {
                //        myErr(this, new myErrEventArgs(5, "error start gp"));
                //    }
                //    return;
                //}
                openvlvfromlist(i);
                List_do.Items.RemoveAt(i);
                list1Additem(i, true);


            }
            List_do.Enabled = true;

        }


        private void List2_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            int i = 0;
            bool b = false;
            i = List_ad.SelectedIndex;
            if (i == -1)
                return;
            b = Status[i];
            string t = null;
            t = List_ad.Text;
            if (b)
            {
                // to off
                List_ad.Items.RemoveAt(i);
                //Call List2.AddItem(cstr[i] + "off", i]
                List_ad.Items.Insert(i, t.Substring(0, t.Length - 3) + "OFF");
            }
            else
            {
                // to on
                List_ad.Items.RemoveAt(i);
                List_ad.Items.Insert(i, t.Substring(0, t.Length - 3) + " ON");
                //Call List2.AddItem(cstr[i] + " on", i]
            }
            //Mcurve1.setLineVisible i, Not b
            Status[i] = !b;

        }


        private void Check1_CheckedChanged(System.Object sender, System.EventArgs e)
        {
            Check_debug.Enabled = false;
            if (Check_debug.CheckState == CheckState.Checked)
                debugMode = true;
            //to not deubg mode
            if (!debugMode)
            {
                if (islinked)
                {
                    //ISRUN = false;
                    ModMain.csystate = csyState.enmReady;
                    reset_Renamed();
                    setState(2);
                }
                //to debug mode
            }
            else
            {
            }
            Check_debug.Enabled = true;
        }


        private void Command1_Click(System.Object sender, System.EventArgs e)
        {
            double stime = 0;
            if (!debugMode)
                return;
            Command_start.Enabled = false;
            Command_stop.Enabled = true;
            mcurve1.clear();
            //ISRUN = true;
            double x = 0;
            double y = 0;
            //Dim result As int
            int i = 0;
            //Dim d As int
            //Dim l As Integer
            //Dim p As Single
            //ISRUN = true;
            ModMain.csystate = csyState.enmDebugSample; 
            stime = ModMain.myTimer();
            for (i = 0; i <= 15; i++)
            {
                isfirst[i] = true;
            }
            mcurve1.setLineCount(16);
            //mcurve1.setscale(0, 0, 30, 10)
            Color[] colors = null;
            colors = new Color[16];
            colors[0] = Color.DarkGray;
            colors[1] = Color.YellowGreen;
            colors[2] = Color.Black;
            colors[3] = Color.Yellow;
            System.Random r = new System.Random();

            for (i = 4; i <= 15; i++)
            {
                double r1 = r.NextDouble() * 255;
                double g1 = r.NextDouble() * 255;
                double b1 = r.NextDouble() * 255;

                colors[i] = Color.FromArgb((int)r1, (int)g1, (int)b1);
            }
            for (i = 0; i <= 15; i++)
            {
                mcurve1.setlinecolor(i, colors[i]);
            }
            mcurve1.draw();
            double powerv, powera, power;
            double oldx = 0;
            while (ModMain.csystate == csyState.enmDebugSample)
            {
                System.Windows.Forms.Application.DoEvents();
                x = ModMain.myTimer() - stime;
                if (x - oldx > 0.5)
                {
                    for (i = 0; i <= 15; i++)
                    {
                        if (Status[i])
                        {
                            y = As2460ocx1.getchanelVolt(i);
                            if (isfirst[i])
                            {
                                mcurve1.starttmpline(x, y, Convert.ToInt16(i));
                                isfirst[i] = false;
                            }
                            else
                            {
                                mcurve1.tmplineaddpoint(x, y, Convert.ToInt16(i));
                            }
                        }
                    }
                    oldx = x;
                    powerv = this.cpower1.getTrueVolt();
                    powera = this.cpower1.getTrueCurrent();
                    power = powerv * powera;
                    this.mYiBiao1.Value = (float)powerv;
                    this.mYiBiao2.Value = (float)powera;
                    this.label1.Text = string.Format("{0:F0}W",power);
                }

            }
            Command_start.Enabled = true;
            Command_stop.Enabled = false;
        }

        private void Command2_Click(System.Object sender, System.EventArgs e)
        {
            ModMain.csystate = csyState.enmReady;
        }

        public void openvlvfromlist(int v)
        {
            this.openVlv2440(v);

        }
        public void closevlvfromlist(int v)
        {
            this.closeVLV2440(v);
        }
        //    Sub anaLoop()
        //        'Call openVlv(vlvindex.总氧)
        //        'Call openVlv(vlvindex.升炉) '关炉
        //        'Call openVlv(vlvindex.排空) '
        //        'Call openVlv((vlvindex.吸尘))
        //        'Call openVlv((vlvindex.炉室))
        //        'Call openVlv(vlvindex.炉后)
        //        'Call openVlv((vlvindex.氧枪))
        //        'Call openVlv(vlvindex.反吹) 'huancui
        //        'Dim c1 As New Collection
        //        'c1.Add(New Cmd(vlvindex.氧枪, kgindex.关))
        //        'c1.Add(New Cmd(vlvindex.反吹, kgindex.关))
        //        'tx_gl.addOneTaskBy(1, 0, 1, AddressOf openCloseVlvs, c1)
        //        '升炉超时 = True
        //        'tx_gl.addOneTaskBy(2, 1, 2, AddressOf cksl, Nothing)
        //        'tx_gl.addOneTaskBy(3, 2, 2, AddressOf cksl, Nothing)
        //        'tx_gl.start()
        //        Exit Sub
        //mexit:
        //        savelogmsg("error run")
        //        RaiseEvent myErr(Me, New myErrEventArgs(curErr, "run error"))
        //    End Sub
        private void tx_taskTimer(int id)
        {
            modLog.savelogmsg("tx_gl" + Convert.ToString(id));
        }



        private void tx_gl_endAllTask()
        {
            setState(3);
            if (isAddSample)
            {
                //ModMain.isAddSample = false;
                ModMain.csystate = csyState.enmReady;
            }
            endTask(this, new endTaskEventArgs());
            if ((shixu1 != null))
            {
                dbrecordshixu(ref shixu1);
            }
        }
        public void openCloseVlvs(List<Cmd> c)
        {
            //Cmd cmd = null;
            foreach (Mcsy.Cmd cmd in c)
            {
                //cmd = cmd_loopVariable;
                if (cmd.isopen)
                {
                    openVlv(cmd.vindex);
                }
                else
                {
                    closeVlv(cmd.vindex);
                }
            }
        }

        public void startdi()
        {
            this.TimerDi.Enabled = true;
        }
        public void stopdi()
        {
            this.TimerDi.Enabled = false;
        }
        public void tiaozhengBase(double timeUsed)
        {
            if (State < 1)
            {
                modLog.savelogmsg("not in state");
                return;
            }
            else
            {
            }
            double[] up = new double[5];
            double[] down = new double[5];
            double des = 0;
            des = 0.0F;
            double derr = 0;
            derr = 0.003F;
            double[] cup = new double[5];
            double[] cld = new double[5];
            //Dim ccurv(4) As double
            int i = 0;
            //Dim numchannel As Integer
            //numchannel = 4
            int[] c = new int[5];
            c[1] = ModMain.getEleChanel("C");
            //.chanel
            c[2] = ModMain.getEleChanel("S");
            //.chanel
            c[3] = ModMain.getEleChanel("C2");
            //.chanel
            c[4] = ModMain.getEleChanel("S2");
            //.chanel
            modLog.savelogmsg("start tiaoling");
            double tmp = 0;
            for (i = 1; i <= ModMain.NUMChanel; i++)
            {
                if (getcenable(i))
                {
                    cup[i] = 10;
                    cld[i] = -10;
                    modLog.savelogmsg("cur:" + Convert.ToString(i) + " " + Convert.ToString(cur[i]));
                    //已经有上次的调零输出
                    if (cur[i] != 0)
                    {
                        tmp = getmultiVolt(c[i]);
                        //获取当前电压
                        if (tmp > 0)
                        {
                            up[i] = cur[i];
                            down[i] = cur[i] - 2.7F * tmp * 2;
                            cur[i] = (up[i] + down[i]) / 2;
                        }
                        else
                        {
                            up[i] = cur[i] - 2.7F * tmp * 2;
                            down[i] = cur[i];
                            cur[i] = (up[i] + down[i]) / 2;
                            //up[i] = cur[i] + 2 * Abs(tmp) '按当前电压设置调整区域上限 cup[i]
                            //down[i] = cur[i] - 2 * Abs(tmp) '按当前电压设置调整区域下限 cld[i]
                        }
                        //上下限取+-10v
                    }
                    else
                    {
                        up[i] = cup[i];
                        down[i] = cld[i];
                    }
                    modLog.savelogmsg(Convert.ToString(i) + " " + Convert.ToString(cur[i]) + " " + Convert.ToString(up[i]) + " " + Convert.ToString(down[i]));
                }
            }
            double[] y = new double[5];
            double t = 0;
            t = ModMain.myTimer();
            bool[] Finish = new bool[5];
            bool allfinish = false;
            int ct = 0;
            while (true)
            {
                ct = ct + 1;
                //记录调整了几次
                for (i = 1; i <= ModMain.NUMChanel; i++)
                {
                    if (getcenable(i))
                    {
                        //未调完
                        if (!Finish[i])
                        {
                            As2460ocx1.newDA(c[i], cur[i]);
                        }
                    }
                }
                Thread.Sleep(1000);
                //等待调整生效
                allfinish = true;
                for (i = 1; i <= ModMain.NUMChanel; i++)
                {
                    if (getcenable(i))
                    {
                        if (!Finish[i])
                        {
                            y[i] = getmultiVolt(c[i]);
                            if (System.Math.Abs(y[i] - des) < derr) { modLog.savelogmsg("des:" + Convert.ToString(i) + ":" + Convert.ToString(y[i])); Finish[i] = true; }
                            //达到目标
                            //大于目标
                            if (y[i] > des)
                            {
                                up[i] = cur[i];
                                //-
                                cur[i] = (up[i] + down[i]) / 2;
                                //小于目标
                            }
                            else if (y[i] < des)
                            {
                                down[i] = cur[i];
                                //+
                                cur[i] = (up[i] + down[i]) / 2;
                            }
                            if (System.Math.Abs(up[i] - down[i]) <= 0.0006) { modLog.savelogmsg(Convert.ToString(i) + ":up=down" + Convert.ToString(y[i])); Finish[i] = true; }
                            //到达边界
                        }
                        allfinish = allfinish & Finish[i];
                    }
                }
                if (ModMain.timePasted(t) < 14)
                {

                }
                else
                {
                    modLog.savelogmsg("timeout ");
                    for (i = 1; i <= ModMain.NUMChanel; i++)
                    {
                        modLog.savelogmsg(Convert.ToString(i) + Convert.ToString(Finish[i]));
                    }
                    break;
                }
                if (allfinish)
                    break;
            }
            modLog.savelogmsg("ct:" + Convert.ToString(ct));
            timeUsed = ModMain.myTimer() - t;
            modLog.savelogmsg("stop tiaoling");
        }
        public double getmultiVolt(int c)
        {
            double r = 0;
            int i = 0;
            int n = 0;
            n = 5000;
            for (i = 0; i <= n - 1; i++)
            {
                r = r + As2460ocx1.getchanelVolt((int)c);
                //'chanel
            }
            return r / n;

        }
        public bool getcenable(int ii)
        {
            Dictionary<int, string> d = null;
            d = new Dictionary<int, string>();
            d.Add(1, "C");
            d.Add(2, "S");
            d.Add(3, "C2");
            d.Add(4, "S2");
            string vele = null;
            vele = d[ii];
            bool r = false;
            //int i = 0;
            //i = 0;
            foreach (NCS.chanel c in ModMain.gchanel)
            {
                if (c.ele == vele)
                {
                    r = c.enable;
                    break;
                }
            }
            return r;
        }

        public void initElse()
        {
            //this.StatusShow.initElse();
            //this.StatusShow.hideControl();
        }

        public void workQi()
        {
                openVlv(vlvindex.enmBili );
                jieqiState = false;
                if (EVjieQi != null)
                {
                    this.EVjieQi(this, new StatusJieQiEventArgs(jieqiState));
                }
               
        }
        public void setmethodpara()
        {
            jx1.setGetOut(ModMain.getEleChanel("C"), ModMain.getEleChanel("C"));
            jx2.setGetOut(ModMain.getEleChanel("C2"), ModMain.getEleChanel("C2"));
            jxN.setGetOut(ModMain.getEleChanel("S"), ModMain.NzeroChannel);
            // ERROR: Not supported in C#: ReDimStatement

            // ERROR: Not supported in C#: ReDimStatement

            adch[0] = ModMain.getEleChanel("C");
            adch[1] = ModMain.getEleChanel("S");
            adch[2] = ModMain.getEleChanel("C2");
            adch[3] = ModMain.getEleChanel("S2");
            multipower1.loadPara();
        }
        public void reverseFurnace1(bool b)
        {
            //open to change ganguo
            if (getVlv(vlvindex.enmKailu))
            {
                //Close
                closeVlv((vlvindex.enmKailu));
                //     MySleep 20000 to change
                if (StatusStr != null)
                {
                    StatusStr(this, new StatusStrEventArgs(ModMain.gtran.MyTranslate("冲洗", "Flush")));
                }
                ModMain.MySleep(10000);
                closeVlv((vlvindex.enmChongxi));
                //RaiseEvent StatusStr("ready")
            }
            else
            {
                As2460ocx1.newDA(ModMain.powerChannel, 0);
                //openVlv((vlvindex.enmChongxi));
                //ModMain.MySleep(1000);
                //closeVlv((vlvindex.enmChongxi));
                openVlv((vlvindex.enmKailu));
                openVlv((vlvindex.enmChongxi));
            }
        }
        public void reverseFurnace()
        {
            if (State < 1)
            {
                if (myErr != null)
                {
                    myErr(this, new myErrEventArgs(3333, "not in state"));
                }
                return;
            }
            //close
            if (kailustate)
            {
                kailustate = false;
                reverseFurnace1(true);
            }
            else
            {
                kailustate = true;
                reverseFurnace1(false);
                //open
            }
        }
        public void jiayang()
        {
            if (State < 1)
            {
                if (myErr != null)
                {
                    myErr(this, new myErrEventArgs(3333, "not in state"));
                }
                return;
            }

            if (tx_gl.isRuning())
            {
                if (myErr != null)
                {
                    myErr(this, new myErrEventArgs(3333, "now is runing task"));
                }
            }
            else
            {
                isAddSample = true;
                if (StatusStr != null)
                {
                    StatusStr(this, new StatusStrEventArgs(ModMain.gtran.MyTranslate("加样", "Add Sample")));
                }

                openVlv((vlvindex.enmFengding));
                //If sblx = 3 Then
                //    MySleep(1000)
                //End If
                openVlv((vlvindex.enmJiayang));
                //
                openVlv((vlvindex.enmChongxi));
                //

                tx_gl.addOneTaskBy(0, 0, 5, task0, null);
                tx_gl.addOneTaskBy(1, 0, 10, task1, null);
                tx_gl.start();
                if (startTask != null)
                {
                    startTask(this, new startTaskEventArgs(0));
                }
            }
        }
        public void task0(List<Cmd> i)
        {
            closeVlv((vlvindex.enmJiayang));
            if (StatusStr != null)
            {
                StatusStr(this, new StatusStrEventArgs(ModMain.gtran.MyTranslate("冲洗", "Purge")));
            }

        }
        public void task1(List<Cmd> i)
        {
            closeVlv((vlvindex.enmChongxi));
            closeVlv((vlvindex.enmFengding));
            setState(3);
            if (StatusStr != null)
            {
                StatusStr(this, new StatusStrEventArgs(ModMain.gtran.MyTranslate("加样结束", "Add Finish")));
            }
        }

        private void TimerDi_Tick(object sender, EventArgs e)
        {
            double u, v, jinghua, zhuanhua, shuiwen;// u As Double, v As Double, jinghua As Double, zhuanhua As Double, shuiwen As Double
            u = As2460ocx1.getchanelVolt(0) * 2;
            if (u < 0) u = 0;
            v = As2460ocx1.getchanelVolt(1) * 300;
            if (v < 0) v = 0;
            jinghua = As2460ocx1.getchanelVolt(10) * 200;
            if (jinghua < 0) jinghua = 0;
            zhuanhua = As2460ocx1.getchanelVolt(9) * 200;
            if (zhuanhua < 0) zhuanhua = 0;
            shuiwen = (As2460ocx1.getchanelVolt(8) / 4 - 1) / 3.9083 * 1000;
            if (shuiwen < 0) shuiwen = 0;
            myStatus(this, new myStatusEventArgs(u, v, jinghua, zhuanhua, shuiwen));
        }
        public void setJieQi(bool vjieqi)
        {
            if (vjieqi)
            {
                jieqi();
            }
            else 
            {
                workQi();
            }
        }

        private void TableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
